package com.smartscreen.homeschoolconnection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smartscreen.baseinfomanage.dto.StudentInfoDTO;
import com.smartscreen.homeschoolconnection.dto.*;
import com.smartscreen.homeschoolconnection.entity.*;
import com.smartscreen.homeschoolconnection.mapper.*;
import com.smartscreen.homeschoolconnection.service.HomeSchoolService;
import com.smartscreen.baseinfomanage.client.BaseInfoClient;
import com.smartscreen.baseinfomanage.dto.StudentInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class HomeSchoolServiceImpl implements HomeSchoolService {
    
    @Autowired
    private ParentStudentBindingMapper bindingMapper;
    
    @Autowired
    private ParentMessageMapper messageMapper;
    
    @Autowired
    private ConversationMapper conversationMapper;
    
    @Autowired
    private ConversationMessageMapper conversationMessageMapper;
    
    @Autowired
    private UserInfoMapper userInfoMapper;
    
    // 使用 Feign 客户端而不是直接注入 Mapper
    @Autowired
    private BaseInfoClient baseInfoClient;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public StudentBindingInfo bindStudent(String parentId, BindStudentRequest request) {
        // 1. 检查是否已经绑定
        QueryWrapper<ParentStudentBinding> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId)
                   .eq("student_number", request.getStudentNumber());
        
        ParentStudentBinding existing = bindingMapper.selectOne(queryWrapper);
        if (existing != null) {
            throw new RuntimeException("该学生已经绑定");
        }
        
        // 2. 通过 Feign 客户端验证学号是否存在
        try {
            // 这里需要根据 BaseInfoClient 的实际方法来调用
            // 假设有一个根据学号查询学生的方法
            List<StudentInfoDTO> students = baseInfoClient.getStudentsByNumbers(Arrays.asList(request.getStudentNumber()));
            
            if (students == null || students.isEmpty()) {
                throw new RuntimeException("学号不存在，请核对后重试");
            }
            
            StudentInfoDTO student = students.get(0);
            
            // 3. 验证身份证号（简单格式验证）
            if (!isValidIdCard(request.getIdCardNumber())) {
                throw new RuntimeException("身份证号格式不正确");
            }
            
            // 4. 创建绑定记录
            ParentStudentBinding binding = new ParentStudentBinding();
            binding.setParentId(parentId);
            binding.setStudentId(student.getStudentId());
            binding.setStudentNumber(student.getStudentNumber());
            binding.setStudentName(student.getName());
            binding.setClassId(student.getClassId());
            // 如果需要班级名称，可以通过 baseInfoClient 获取班级信息
            binding.setClassName("班级名称"); // 这里可以进一步优化
            binding.setIdCardNumber(request.getIdCardNumber());
            
            bindingMapper.insert(binding);
            
            // 5. 返回绑定信息
            StudentBindingInfo result = new StudentBindingInfo();
            result.setStudentId(binding.getStudentId());
            result.setStudentName(binding.getStudentName());
            result.setClassId(binding.getClassId());
            result.setClassName(binding.getClassName());
            
            return result;
            
        } catch (Exception e) {
            throw new RuntimeException("验证学生信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 简单的身份证号格式验证
     * @param idCard 身份证号
     * @return 是否有效
     */
    private boolean isValidIdCard(String idCard) {
        if (idCard == null || idCard.trim().isEmpty()) {
            return false;
        }
        // 简单验证：18位数字或17位数字+X
        return idCard.matches("^[0-9]{17}[0-9Xx]$");
    }
    
    @Override
    public List<StudentBindingInfo> getBindings(String parentId) {
        QueryWrapper<ParentStudentBinding> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        
        List<ParentStudentBinding> bindings = bindingMapper.selectList(queryWrapper);
        
        return bindings.stream().map(binding -> {
            StudentBindingInfo info = new StudentBindingInfo();
            info.setStudentId(binding.getStudentId());
            info.setStudentName(binding.getStudentName());
            info.setClassName(binding.getClassName());
            return info;
        }).collect(Collectors.toList());
    }
    
    @Override
    public Map<String, Object> getMessages(String parentId, Integer page, Integer pageSize, String type) {
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        
        QueryWrapper<ParentMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        
        if (StringUtils.hasText(type)) {
            queryWrapper.eq("type", type);
        }
        
        queryWrapper.orderByDesc("sent_at");
        
        Page<ParentMessage> messagePage = new Page<>(page, pageSize);
        Page<ParentMessage> result = messageMapper.selectPage(messagePage, queryWrapper);
        
        List<MessageInfo> messages = result.getRecords().stream().map(message -> {
            MessageInfo info = new MessageInfo();
            info.setMessageId(message.getMessageId());
            info.setType(message.getType());
            info.setTitle(message.getTitle());
            info.setContent(message.getContent());
            info.setIsRead(message.getIsRead());
            info.setSentAt(message.getSentAt());
            
            // 解析关联数据
            if (StringUtils.hasText(message.getRelatedData())) {
                try {
                    Map<String, Object> related = objectMapper.readValue(
                        message.getRelatedData(), 
                        new TypeReference<Map<String, Object>>() {}
                    );
                    info.setRelated(related);
                } catch (Exception e) {
                    // 忽略解析错误
                }
            }
            
            return info;
        }).collect(Collectors.toList());
        
        Map<String, Object> response = new HashMap<>();
        response.put("total", result.getTotal());
        response.put("messages", messages);
        
        return response;
    }
    
    @Override
    public void markMessageAsRead(String messageId) {
        QueryWrapper<ParentMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("message_id", messageId);
        
        ParentMessage message = messageMapper.selectOne(queryWrapper);
        if (message != null) {
            message.setIsRead(true);
            messageMapper.updateById(message);
        }
    }
    
    @Override
    public Map<String, String> sendMessageToTeacher(String parentId, SendMessageRequest request) {
        // 查找或创建对话
        QueryWrapper<Conversation> convQueryWrapper = new QueryWrapper<>();
        convQueryWrapper.eq("parent_id", parentId)
                       .eq("teacher_id", request.getRecipientId())
                       .eq("student_id", request.getStudentId());
        
        Conversation conversation = conversationMapper.selectOne(convQueryWrapper);
        
        if (conversation == null) {
            conversation = new Conversation();
            conversation.setConversationId("conv_" + System.currentTimeMillis());
            conversation.setParentId(parentId);
            conversation.setTeacherId(request.getRecipientId());
            conversation.setStudentId(request.getStudentId());
            conversationMapper.insert(conversation);
        }
        
        // 创建消息
        ConversationMessage message = new ConversationMessage();
        message.setMessageId("msg_" + System.currentTimeMillis());
        message.setConversationId(conversation.getConversationId());
        message.setSenderId(parentId);
        message.setSenderType("parent");
        message.setContent(request.getContent());
        message.setIsRead(false);
        message.setSentAt(LocalDateTime.now());
        
        conversationMessageMapper.insert(message);
        
        Map<String, String> result = new HashMap<>();
        result.put("conversationId", conversation.getConversationId());
        result.put("messageId", message.getMessageId());
        
        return result;
    }
    
    @Override
    public List<ConversationInfo> getConversations(String userId, String userType) {
        QueryWrapper<Conversation> queryWrapper = new QueryWrapper<>();
        
        if ("parent".equals(userType)) {
            queryWrapper.eq("parent_id", userId);
        } else if ("teacher".equals(userType)) {
            queryWrapper.eq("teacher_id", userId);
        }
        
        List<Conversation> conversations = conversationMapper.selectList(queryWrapper);
        
        return conversations.stream().map(conv -> {
            ConversationInfo info = new ConversationInfo();
            info.setConversationId(conv.getConversationId());
            
            // 获取对话另一方信息
            String otherUserId = "parent".equals(userType) ? conv.getTeacherId() : conv.getParentId();
            QueryWrapper<UserInfo> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_id", otherUserId);
            UserInfo otherUser = userInfoMapper.selectOne(userQueryWrapper);
            
            if (otherUser != null) {
                ConversationInfo.OtherPartyInfo otherParty = new ConversationInfo.OtherPartyInfo();
                otherParty.setUserId(otherUser.getUserId());
                otherParty.setName(otherUser.getName());
                otherParty.setAvatarUrl(otherUser.getAvatarUrl());
                info.setOtherParty(otherParty);
            }
            
            // 获取最后一条消息
            QueryWrapper<ConversationMessage> msgQueryWrapper = new QueryWrapper<>();
            msgQueryWrapper.eq("conversation_id", conv.getConversationId())
                          .orderByDesc("sent_at")
                          .last("LIMIT 1");
            
            ConversationMessage lastMsg = conversationMessageMapper.selectOne(msgQueryWrapper);
            if (lastMsg != null) {
                ConversationInfo.LastMessageInfo lastMessage = new ConversationInfo.LastMessageInfo();
                lastMessage.setContent(lastMsg.getContent());
                lastMessage.setSentAt(lastMsg.getSentAt());
                info.setLastMessage(lastMessage);
            }
            
            // 计算未读消息数
            QueryWrapper<ConversationMessage> unreadQueryWrapper = new QueryWrapper<>();
            unreadQueryWrapper.eq("conversation_id", conv.getConversationId())
                             .eq("is_read", false)
                             .ne("sender_id", userId);
            
            Long unreadCount = conversationMessageMapper.selectCount(unreadQueryWrapper);
            info.setUnreadCount(unreadCount.intValue());
            
            return info;
        }).collect(Collectors.toList());
    }
    
    @Override
    public List<MessageInfo> getConversationMessages(String conversationId) {
        QueryWrapper<ConversationMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("conversation_id", conversationId)
                   .orderByAsc("sent_at");
        
        List<ConversationMessage> messages = conversationMessageMapper.selectList(queryWrapper);
        
        return messages.stream().map(message -> {
            MessageInfo info = new MessageInfo();
            info.setMessageId(message.getMessageId());
            info.setContent(message.getContent());
            info.setIsRead(message.getIsRead());
            info.setSentAt(message.getSentAt());
            return info;
        }).collect(Collectors.toList());
    }
}